//
//  UIImage+RadiusCorner.swift
//  
//  图片圆角高效优化
//  Created by XFGuo on 2019/2/15.
//  Copyright © 2019 China Electronic Intelligence System Technology Co., Ltd. All rights reserved.
//

import Foundation

extension UIImage {
    func imageWithCornerRadius(_ radius : CGFloat, _ size : CGSize) -> UIImage {
        /* 当前UIImage的可见绘制区域 */
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        /* 创建基于位图的上下文 */
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        /* 在当前位图上下文添加圆角绘制路径 */
        let currentContext = UIGraphicsGetCurrentContext()
        let BPath = UIBezierPath(roundedRect: rect, cornerRadius: radius).cgPath
        currentContext?.addPath(BPath)
        /* 当前绘制路径和原绘制路径相交得到最终裁剪绘制路径 */
        currentContext?.clip();
        /* 绘制 */
        self.draw(in: rect)
        /* 取得裁剪后的image */
        let image = UIGraphicsGetImageFromCurrentImageContext();
        /* 关闭当前位图上下文 */
        UIGraphicsEndImageContext();
        return image ?? UIImage()
    }
}
